package com.nq.service;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.nq.utils.smsUtil.AbroadSmsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.ExecutorService;

@Service
public class SmsService {

    private static final Logger logger = LoggerFactory.getLogger(SmsService.class);
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    AbroadSmsUtil abroadSmsUtil;

    private ExecutorService executorService = ThreadUtil.newExecutor(1, 1);

    /**
     * 发送短信验证码
     * @param userId
     * @param content
     */
    public void sendMsgByUserId(String userId, String content) {
        executorService.execute(() -> {
            String phone = jdbcTemplate.queryForObject("select phone from user where id = ?", String.class, userId);
            if (StrUtil.isBlank(phone)) {
                logger.info("{}未配置手机号", userId);
                return;
            }
            String result = abroadSmsUtil.sendSms(phone, content);
            jdbcTemplate.update("insert into sms_log (userid, phone, content, result) values (?, ?, ?, ?)", userId, phone, content, result);
        });

    }
}
